<?php

class Coupon_codesApp extends BackendApp {

    var $_couponCodes_mod;
    var $_couponsn_mod;
    var $_goods_mod;

    /**
     * @var string 店铺model
     */
    protected $_store_mod;

    /**
     * @var string 地区model
     */
    protected $_region_mod;    

    function __construct() {
        $this->CouponApp();
    }

    function CouponApp() {
        parent::BackendApp();
        $this->_couponCodes_mod = & m('coupon_codes');
        $this->_couponsn_mod = & m('couponsn');
        $this->_goods_mod = & m('goods');
        $this->_store_mod =& m('store');
        $this->_region_mod =& m('region');        
    }

    /**
     * 默认列表
     */
    function index()
    {
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 's.store_name',
                // name值必须设置，否则不会出现$conditions条件，大坑...
                'name' => 'store_name',
                'equal' => 'like',
            ),
            array
            (
                'field' => 'coupon_codes.not_before',
                'name' => 'not_before',
                'equal' => '>=',
            ),
            array
            (
                'field' => 'coupon_codes.not_after',
                'name' => 'not_after',
                'equal' => '<=',
            )
            )
        );

        // 更新排序
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc'))) {
                $sort = 'not_after';
                $order = 'asc';
            }
        } else {
            $sort = 'not_after';
            $order = 'asc';
        }

        // 处理分页
        $page = $this->_get_page(20);
        $coupon_codes_list = $this->_couponCodes_mod->find(array(
            'fields' => 'coupon_codes.*, s.store_name, s.store_id, storestock.stock_name',
            'conditions' => "1=1 " . $conditions,
            'join' => 'belongs_to_store, belongs_to_storestock',
            'order' => "$sort $order",
            'limit' => $page['limit'],
            'count' => true,
        ));

        // 格式化显示type字段
        foreach ($coupon_codes_list as $k => $item) {
            // 活动类型
            $coupon_codes_list[$k]['type'] = Coupon_codesModel::$typeMap[$item['type']];
            // 活动描述
            $coupon_codes_list[$k]['description'] = $this->_couponCodes_mod->getDescription($item['id']);
        }

        $page['item_count'] = $this->_couponCodes_mod->getCount();
        $this->_format_page($page);
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('page_info', $page);
        $this->assign('coupon_codes_list', $coupon_codes_list);
        // 引入前端资源
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        // 显示模板
        $this->display('coupon_codes.list.html');
    }

    // 注释原列表方法
    // function index() {

    //     $conditions = $this->_get_query_conditions(array(
    //         array(
    //             'field' => 'store_name',
    //             'equal' => 'like',
    //         ),
    //     ));
    //     //更新排序
    //     if (isset($_GET['sort']) && isset($_GET['order'])) {
    //         $sort = strtolower(trim($_GET['sort']));
    //         $order = strtolower(trim($_GET['order']));
    //         if (!in_array($order, array('asc', 'desc'))) {
    //             $sort = 'end_time';
    //             $order = 'asc';
    //         }
    //     } else {
    //         $sort = 'end_time';
    //         $order = 'asc';
    //     }

    //     $page = $this->_get_page(20);
    //     $coupon_list = $this->_couponCodes_mod->find(array(
    //         'fields' => 'coupon_codes.*,s.store_name,s.store_id',
    //         'conditions' => "1=1 " . $conditions,
    //         'join' => 'belongs_to_store',
    //         'order' => "$sort $order",
    //         'limit' => $page['limit'],
    //         'count' => true,
    //     ));

    //     $page['item_count'] = $this->_couponCodes_mod->getCount();
    //     $this->_format_page($page);
    //     $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
    //     $this->assign('page_info', $page);
    //     $this->assign('coupon_list', $coupon_list);
    //     $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
    //         'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
    //     $this->display('coupon_codes.index.html');
    // }

    function view(){
        $ad_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $discountModel = &m('discount');
        if (!$ad_id){
            $this->show_warning('no_such_coupon_codes_id');
            return;
        }

        if (!IS_POST){
            $find_data     = $this->_couponCodes_mod->get(array('conditions'=>'id = '.$ad_id));
            if (empty($find_data))
            {
                $this->show_warning('no_such_coupon_codes');
                return;
            }
            $sql = "SELECT * from ecm_discount WHERE coupon_codes_id =".$ad_id." GROUP by goods_id";

            $info = $discountModel->db->query($sql);
            while ($chat = $discountModel->db->fetchRow($info)) {
                $chat_list[] = $chat;
            }

            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js'
            ));
            $goods_spec = & m('goodsspec');
            if(!empty($chat_list)){
                $temp = $chat_list;
                $goods_id = '';
                $temp_goods = array();
                foreach ($temp as $k => $v){
                    if($k == 0){
                        $goods_id = $v['goods_id'];
                    }else{
                        $goods_id .= ','.$v['goods_id'];
                    }
                    $temp_goods[$k]['goods_id'] = $v['goods_id'];
                    $c = $this->_goods_mod->get($v['goods_id']);
                    $temp_goods[$k]['goods_name'] = $c['goods_name'];
                    $temp_goods[$k]['default_image'] = WEB_PHOTO_SRC . "/" . $c['default_image'];

                    $retult = $goods_spec->find(array('conditions'=>'goods_id = '.$v['goods_id']));
                    //声明一个库存数
                    $inventory = 0;
                    foreach ($retult as $key => $vvalue) {
                        $inventory += $vvalue['stock'];
                    }
                    //总库存
                    $temp_goods[$k]['total_inventory'] = $inventory;
                }
                $infoArr['goods'] = $temp_goods;
            }
            $infoArr['goods_id'] = $goods_id;
            //仓库
            $storeStock = &m('storestock');
            $storeList = array_values($storeStock->find());
            $find_dataStoreStock = explode(',',$find_data['storestock_id']);
            foreach($storeList as $k=>$v){
                $storeList[$k]['checked'] = '';
                if(in_array($v['storestock_id'],$find_dataStoreStock)){
                    $storeList[$k]['checked'] = 'checked';
                }
            }
            $this->assign('find_dataStoreStock',json_encode($find_dataStoreStock));
            $this->assign('storeStock',$storeList);
            $this->assign('banner', $infoArr);
            $this->assign('storestock_id',$find_data['storestock_id']);
            $this->assign('find_data', $find_data);
            $this->display('coupon_codes.form.html');
        }else{
            $find_data     = $discountModel->get(array('conditions'=>'coupon_codes_id = '.$ad_id));
            if (empty($ad_id)){
                $this->show_warning('no_such_coupon');
                return;
            }
            //去重
            $goodsArr = explode(',',$_POST['goods_id']);
            $goods_specModel = &m('goodsspec');
            $goodsModel = &m('goods');
            $myTax = &m('my_tax');
            if(!empty($goodsArr)){
                $delete = $discountModel->drop($ad_id);
                $newGoodsArr = array_unique($goodsArr);
                $storestock_id = implode(',',$_POST['storestock_id']);
                $ids = '';
                $this->_couponCodes_mod->edit($ad_id,array('value'=>$_POST['value'],'storestock_id'=>$storestock_id));
                //拿到商品id进行查询所有符合仓库条件的规格
                foreach($newGoodsArr as $k=>$v){
                    $goodsSpecInfo = $goods_specModel
                        ->find(array(
                            'conditions'=>'goods_id = '.$v.' AND spec_3value in ('.$storestock_id.')'
                        ));
                    $conditions = ' AND g.goods_id = '.$v;
                    $taxInfo = $myTax->get(array(
                        'fields' => 'consolidated_tax',
                        'join' => 'belongs_to_goods',
                        'conditions'    => '1=1 ' . $conditions,
                    )); //找出每一件商品的税率
                    foreach($goodsSpecInfo as $key=>$value){
                        $data = array(
                            'goods_id' => $v,
                            'coupon_codes_id'=>$ad_id,
                            'spec_id'  => $value['spec_id'],
                            'storestock_id' => $value['spec_3value']
                        );
                        //查看该活动该规格中是否已经存在
                        $info = $discountModel
                            ->get(array(
                                'conditions'=>'goods_id = '.$v.' AND coupon_codes_id = '.$ad_id.' AND spec_id = '.$value['spec_id']
                            ));
                        if($value['price'] > 0){
                            $saveData['discount_price'] = $value['price'] * $_POST['value'];
                        }
                        if($value['tax_price'] > 0 ){
                            /**暂时先这么写  感觉有问题   李晨的逻辑 ！！！！！！！！！！！！*/
                            $saveData['tax_discount_price'] = $saveData['discount_price'] * $taxInfo['consolidated_tax'];
                        }
                        $goods_specModel->edit($value['spec_id'],$saveData);
                        if(empty($info)){
                            $discountModel->add($data);
                        }else{
                            continue;
                        }
                    }
                }
                if ($discountModel->has_error()){
                    $this->show_warning($discountModel->get_error());
                    return;
                }else{
                    $this->admin_log("修改活动专题",1);
                }

                $this->show_message('保存成功',
                    'back_list',        'index.php?app=coupon_codes',
                    'edit_again',    'index.php?app=coupon_codes&amp;act=view&amp;id=' . $ad_id);
            }
        }

    }

    //查询商品规格信息
    public function goodsSpecInfo(){
        $goods_id = $_POST['goods_id'];
        $code = -1;
        $msg = '参数错误';
        if($goods_id){
           $goodsSpecModel = &m('goodsspec');

           $info = $goodsSpecModel->find(array('conditions'=>'goods_id = '.$goods_id));
           $msg = '信息有误';
           if(!empty($info)){
               $code = 1;
               $msg = array_values($info);
           }
        }
        $arr = array('code'=>$code,'msg'=>$msg);
        echo json_encode($arr);
        exit();
    }


    function drop() {
        $coupon_id = isset($_GET['id']) ? intval($_GET['id']) : '';
        if (empty($coupon_id)) {
            $this->show_warning('no_coupon');
            return;
        }
        $coupon = $this->_couponCodes_mod->get($coupon_id);
        if (empty($coupon)) {
            $this->show_warning('no_coupon');
            return;
        }
        $this->_couponCodes_mod->drop($coupon_id);
        if ($this->_couponCodes_mod->has_error()) {
            $this->show_warning($this->_couponCodes_mod->get_error());
            return;
        }
        $info = &m('discount')->drop('coupon_codes_id =' . $coupon_id);
        $this->show_message('drop_ok', 'back_list', 'index.php?app=coupon_codes');
    }
    
    //异步修改数据
   function ajax_col()
   {
       $id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
       $column = empty($_GET['column']) ? '' : trim($_GET['column']);
       $value  = isset($_GET['value']) ? trim($_GET['value']) : '';
       $data   = array();
       if (in_array($column ,array('mall_recommended','sort_order')))
       {
           $data[$column] = $value;
           $this->_couponCodes_mod->edit($id, $data);
           if(!$this->_couponCodes_mod->has_error())
           {
               echo ecm_json_encode(true);
           }
       }
       else
       {
           return ;
       }
       return ;
   }

    /**
     * 图片上传
     * @param $sort_id
     * @return bool|string
     */
    function _upload($file,$str){
        require_once '../includes/aliyunOss/samples/Common.php';
        $image = $file[$str];
        $imageName = date("YmdHis", time()) . rand(1000,10000);
        $path = 'data/files/mall/coupon_codes/'.$str;

        if ($image['error'] == UPLOAD_ERR_NO_FILE) { // 没有文件被上传
            return '';
        }
        import('uploader.lib');             //导入上传类
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
        $uploader->addFile($_FILES[$str]); //上传logo
        if (!$uploader->file_info()) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=coupon_codes&amp;act=index');
            return false;
        }
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        if (!$file_path = $uploader->save($path,$imageName)) {   //保存到指定目录，并以指定文件名$ad_id存储
            $this->show_message('上传文件失败！');
            return false;
        }
        $ossClient = new \common;
        $r = $ossClient->putObjectFile('../'.$file_path,$file_path);
        if(!$r['info'] || $r['info']['http_code'] != 200){
            $this->show_message('上传oss失败！');
            return false;
        }
        unlink('../'.$file_path);
        return $file_path;
    }


    /**
     * 新增
     */
    function add()
    {
        // 逻辑
        if (!IS_POST) {
            /* 显示新增表单 */
            $yes_or_no = array(
                1 => Lang::get('yes'),
                0 => Lang::get('no'),
            );

            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));

            // 获取关键数据
            $typesAndStores = $this->getTypesAndStores();
            // 引入前端资源
            $this->import_resource(['script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css']);

            // 赋值
            $this->assign('types', $typesAndStores['types']);
            $this->assign('yes_or_no', $yes_or_no);
            $this->assign('stores', $typesAndStores['stores']);
            $this->display('coupon_codes.add-edit.form.html');

        } else {

            // 如果是post提交
            // 验证结果
            $check_result = $this->checkPostParams();
            if ($check_result === false) {
                return false;
            }

            // 接收参数值，以下为必传参数
            $data = array(
                'store_id' => $_POST['store_id'],                
                'name' => $_POST['name'],
                'type' => $_POST['type'],
                'value' => $_POST['value'],
                'total' => $_POST['total'],
                'min_amount' => $_POST['min_amount'],
                'not_before' => $_POST['not_before'],
                'not_after' => $_POST['not_after'],
                'enabled' => $_POST['enabled'],
            );

            if (!$coupon_codes_id = $this->_couponCodes_mod->add($data)) {  //获取新增ID
                $this->show_warning($this->_couponCodes_mod->get_error());
                return false;
            } else {
                $this->admin_log("新增促销活动[" . $_POST['name'] . "]", 1);
            }

            // 处理上传的LOGO
            $coupon_codes_logo = $this->_upload($_FILES,'ico');
            if ($coupon_codes_logo === false) {
                return false;
            }

            $coupon_codes_logo && $this->_couponCodes_mod->edit($coupon_codes_id, array('ico' => $coupon_codes_logo)); //将logo地址记下

            $this->show_message('add_coupon_codes_successed', 'back_list', 'index.php?app=coupon_codes', 'continue_add', 'index.php?app=coupon_codes&amp;act=add');
        }
    }    

    /**
     *    编辑文章
     *
     * @return bool
     * @author    Hyber
     */
    function edit()
    {
        // 逻辑按照其他模块的来，主要参考的article，就不写注释了
        $coupon_codes_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$coupon_codes_id) {
            $this->show_warning('data_not_exist');
            return;
        }
        if (!IS_POST) {

            // 获取关键数据，获取所有的类型和店铺集合
            $typesAndStores = $this->getTypesAndStores();

            $find_data = $this->_couponCodes_mod->find($coupon_codes_id);
            if (empty($find_data)) {
                $this->show_warning('data_not_exist');

                return;
            }
            $coupon_codes = current($find_data);
            if ($coupon_codes['ico']) {
                $coupon_codes['ico'] = WEB_PHOTO_SRC."/" . $coupon_codes['ico'] . '?v=' . time();
            }
            $types = $typesAndStores['types'];
            $stores = $typesAndStores['stores'];
            $this->assign("id", $coupon_codes_id);
            // 引入前端资源
            $this->import_resource(['script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css']);            

            $this->assign('coupon_codes', $coupon_codes);
            $this->assign('types', $types);
            $this->assign('stores', $stores);

            $this->display('coupon_codes.add-edit.form.html');
        } else {

            // 验证结果
            $check_result = $this->checkPostParams();
            if ($check_result === false) {
                return false;
            }

            // 接收参数值，以下为必传参数
            $data = array(
                'name' => $_POST['name'],
                'type' => $_POST['type'],
                'store_id' => $_POST['store_id'],
                'value' => $_POST['value'],
                'total' => $_POST['total'],
                'min_amount' => $_POST['min_amount'],
                'not_before' => $_POST['not_before'],
                'not_after' => $_POST['not_after'],
                'enabled' => $_POST['enabled'],
            );

            $coupon_codes_logo = $this->_upload($_FILES,'ico');
            $coupon_codes_logo && $data['ico'] = $coupon_codes_logo;
            if ($coupon_codes_logo === false) {
                return;
            }

            $this->_couponCodes_mod->edit($coupon_codes_id, $data);
            if ($this->_couponCodes_mod->has_error()) {
                $this->show_warning($this->_couponCodes_mod->get_error());
                return;
            } else {
                $this->admin_log("修改活动[" . $_POST['name'] . "]", 1);
            }          

            $this->show_message('edit_coupon_codes_successed', 'back_list', 'index.php?app=coupon_codes', 'edit_again', 'index.php?app=coupon_codes&amp;act=edit&amp;id=' . $coupon_codes_id);
        }
    }


    /**
     * 取出所有活动类型+1、2级地区列表
     * @return array
     */
    function getTypesAndStores()
    {
        // 逻辑
        // 活动类型
        $types = Coupon_codesModel::$typeMap;

        // 所有店铺列表
        $allStores = $this->_store_mod->findAll(array(
            // 只取出店铺id，店铺名，所属地区id，剩下的都没用
            'fields' => 'store_id, store_name, region_id',
        ));

        // 所有地区列表
        $allDefaultRegions = $this->_region_mod->getFirstAndSecondLevelRegions();
        // 打乱key值，让默认key值取region_id，方便后续操作
        $allRegions = array();
        foreach ($allDefaultRegions as $region) {
            $allRegions[$region['region_id']] = $region;
        }

        // 一级&二级地区列表，只包含ID列表的
        $regions = array_column($allDefaultRegions, 'region_id');

        // 然后把店铺列表中属于一级&二级地区列表的店铺筛选出来，放在新数组$stores中
        $stores = array();
        foreach ($allStores as $store) {
            if (in_array($store['region_id'], $regions)) {
                // 给$store添加一个地区上级ID-parent_id，便于后续操作
                $store['parent_region_id'] = $allRegions[$store['region_id']]['parent_id'];
                // 取store_id作为key
                $stores[$store['store_id']] = $store;
            }
        }

        // 返回
        return array(
            'types' => $types,
            'stores' => $stores,
        );
    }

    /**
     * 验证post提交
     * @return bool
     */
    private function checkPostParams()
    {
        // 逻辑
        // 如果是post提交
        // 活动名称不能为空
        if (empty(trim($_POST['name']))) {
            $this->show_warning('活动名称不能为空');
            return false;
        }

        // 类型不能为空
        if (empty(trim($_POST['type']))) {
            $this->show_warning('活动类型不能为空');
            return false;
        }

        // 折扣值不能为空
        if (!is_numeric($_POST['value'])) {
            $this->show_warning('折扣值不合法');
            return false;
        }

        // 开始时间不能为空
        if (empty($_POST['not_before'])) {
            $this->show_warning('开始时间不能为空');
            return false;
        }

        // 结束时间不能为空
        if (empty($_POST['not_after'])) {
            $this->show_warning('结束时间不能为空');
            return false;
        }

        // 如果都验证通过了，返回true
        return true;
    }

}

?>
